package com.cddata;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;

import com.cddata.entity.Contents;
import com.cddata.util.DBOperation;
import com.cddata.util.HibernateUtil;

@SuppressWarnings("serial")
public class AvailableCDs extends JPanel implements ActionListener,ItemListener{
	public AvailableCDs( ) {
		display();
	}

	private void display( ) {
		setMaximumSize(new Dimension(DBOperation.getHelperBean().getMainWindowWidth()-100,DBOperation.getHelperBean().getMainWindowHieght()-100));
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		add(createCDListPanel());
		add(createButtonPanel());
		setVisible(true);
	}

	@SuppressWarnings("unchecked")
	private JPanel createCDListPanel () {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Query query = null;
		String queryStr = " SELECT DISTINCT contentHolder FROM Contents order by contentHolder asc ";
		query = session.createQuery(queryStr) ;
		List contentList = query.list();
		JPanel cdListPanel = new JPanel(new GridLayout(contentList.size()/4,4));
		cdListPanel.setBorder(new TitledBorder(""));
		// dimension for the header panel to set the size of the panel
		Dimension dimension = new Dimension(DBOperation.getHelperBean().getMainWindowWidth()-100, 40);
		add(DBOperation.getHelperBean().createHeaderPanel("Available Cds ..."+contentList.size(), dimension ));
		for( Iterator<String> it = contentList.iterator(); it.hasNext();) {
			String content = it.next();
			JCheckBox checkBox = new JCheckBox(content);
			checkBox.addItemListener(this);
			cdListPanel.add(checkBox);
		}
		cdListPanel.setMaximumSize(new Dimension(DBOperation.getHelperBean().getMainWindowWidth(),DBOperation.getHelperBean().getMainWindowHieght()));
		return cdListPanel;
	}

	private JPanel createButtonPanel () {
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBorder(new TitledBorder(""));
		JButton checkAll = new JButton("Check...");
		JButton unCheckAll = new JButton("UnCheck");
		JButton showBut = new JButton("Show...");
		JButton delBut = new JButton("Delete");
		JButton addBut = new JButton("Add...");

		addBut.addActionListener(this);
		delBut.addActionListener(this);
		checkAll.addActionListener(this);
		unCheckAll.addActionListener(this);
		showBut.addActionListener(this);

		checkAll.setToolTipText("Select All");
		unCheckAll.setToolTipText(" Uncheck all selected");
		buttonPanel.setMaximumSize(new Dimension(DBOperation.getHelperBean().getMainWindowWidth()-100,50));
		buttonPanel.add( checkAll );
		buttonPanel.add( unCheckAll);
		buttonPanel.add(showBut);
		buttonPanel.add(addBut);
		buttonPanel.add(delBut);
		return buttonPanel;
	}

	public void actionPerformed( ActionEvent ae ) {
		String action = ae.getActionCommand();
		if( "Show...".equalsIgnoreCase( action ) ) {
			if( selectedSet.size() == 0 ) {
				JOptionPane.showMessageDialog(this,"Please select atleast one check box to display");
				return;
			}
			DBOperation.getHelperBean().hideContainer();
			SearchResult searchResult = new SearchResult();
			searchResult.setList(showContents());
			searchResult.display();
			DBOperation.getHelperBean().addContainer(searchResult);
			searchResult = null;
		} else if( "Check...".equalsIgnoreCase(action )) {
			checkUnCheck( action );
		} else if( "UnCheck".equalsIgnoreCase(action)){
			checkUnCheck(action);
		} else if( "Add...".equalsIgnoreCase(action)) {
			DBOperation.getHelperBean().hideContainer();
			DBOperation.getHelperBean().addContainer(new FileUpload());
		} else if( "Delete".equalsIgnoreCase(action)) {
			if( selectedSet.size() == 0 ) {
				JOptionPane.showMessageDialog(this,"Please select atleast one check box to display");
				return;
			} else {
				performDelete();
				DBOperation.getHelperBean().hideContainer();
				DBOperation.getHelperBean().addContainer(new AvailableCDs());
			}
		}
	}

	/**
	 * performs the operation when the check and uncheck button is triggered
	 */
	private void checkUnCheck( String aAction) {
		// this is the root level panel 
		Component[] comp = getComponents();
		for( Component c: comp ) {
			if( c instanceof JPanel ) {
				// check for components in the current panel as a container
				Component[] comps = ((Container)c).getComponents();
				int count = 0;
				count++;
				for( Component jc : comps ) {
					if(jc instanceof JCheckBox ) {
						JCheckBox cBox = (JCheckBox) jc;
						if( "Check...".equalsIgnoreCase(aAction)) {
							if( !cBox.isSelected() )
								cBox.setSelected(true);
						} else if( "UnCheck".equalsIgnoreCase(aAction)) {
							cBox.setSelected(false);
						}
					}
				}
			}
		}
	}

	public void itemStateChanged(ItemEvent ie ) {
		int action = ie.getStateChange();
		JCheckBox itemName = (JCheckBox)ie.getItem();
		if( action == 1 ) {
			selectedSet.add(itemName.getText());
		} else {
			selectedSet.remove(itemName.getText());
		}
	}

	@SuppressWarnings("unchecked")
	private List showContents() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(Contents.class);
		String [] selectedCDStr = new String[selectedSet.size()];
		int count = 0;
		for( Iterator it = selectedSet.iterator(); it.hasNext();) {
			selectedCDStr[count] = it.next().toString();
			count++;
		}
		criteria.add(Expression.in("contentHolder", selectedCDStr));
		// code is copied at the end in showcontent
		List list = criteria.list();
		session.close();
		return list;
	}

	@SuppressWarnings("unchecked")
	private void performDelete() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transact = session.beginTransaction();
		int count = 0;
		StringBuffer queryStr = new StringBuffer( " Delete from Contents where contentHolder in ( " );

		for( Iterator it = selectedSet.iterator(); it.hasNext();) {
			if( selectedSet.size()==1) {
				queryStr.append("'"+it.next()+"')" );	
			} else {
				count++;
				if( count == selectedSet.size() ) {
					queryStr.append("'"+it.next()+"')" );
				} else {
					queryStr.append("'"+it.next()+"'," );
				}
			}
		}
		Query query = session.createQuery(queryStr.toString());
		int i = query.executeUpdate();
		transact.commit();
		session.close();
		JOptionPane.showMessageDialog(this,"Deleted '" + i + "' records from '" + selectedSet.size() + "' CD(s)");
		return;
	}
	//	for stioring the selcted cd items 
	HashSet<String> selectedSet = new HashSet<String>();
	JLabel headingLabel = null; 
}